const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const superagent = require('superagent');
require("superagent-charset")(superagent);
const sectorModel = require('../model/sector');



async function getSectors(){
     let result = await superagent.get("https://push2.eastmoney.com/api/qt/clist/get")
        .set('user-agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36')
        .set('Content-Type','application/json')
        .query({
            fs: "m:90+e:2",
            fields: "f1,f12,f13,f14,f3,f62,f2,f3,f605",
            fid: "f62",
            po: 1,
            pn: 1,
            pz: 100,
            np: 1,
            fltt: 2,
            invt: 2,
            ut: "f057cbcbce2a86e2866ab8877db1d059"
        })

        return result.body;
}

router.get('/update',(req,res)=>{
    getSectors().then(async result=>{

        let sectors = [];

        result.data.diff.forEach(a=>{
            sectors.push({
                name: a.f14,
                code: a.f12
            })
        })

        await sectorModel.insertMany(sectors,{
            ordered: false
        })

        res.send(result)

    })
})

router.get('/find',async (req,res)=>{
    let rows = await sectorModel.find().select("-_id -__v -news");

    res.send({
        code: 0,
        data: {
            rows
        }
    })
})

router.get('/findWithNews',async (req,res)=>{
    let rows = await sectorModel.find().select("-_id -__v");

    res.send({
        code: 0,
        data: {
            rows
        }
    })
})

router.get('/getNews',async (req,res)=>{

    let code = req.query.code;

     let result = await superagent.get("https://np-listapi.eastmoney.com/comm/wap/getListInfo")
        .set('user-agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36')
        .set('Content-Type','application/json')
        .query({
            "client": "wap",
            "type": "1",
            "pageIndex": 1,
            "pageSize": 20,
            "mTypeAndCode": "90."+code,
            "_": new Date().getTime()
        })


        try {
            let sector = await sectorModel.findOne({
                code: code
            }).exec();

            sector.news = JSON.stringify(result.body.data.list);
            await sector.save();

        } catch (e){
            console.error(e)
        }


        res.send({
            code: 0,
            data: result.body.data.list
        });
})


module.exports = router;
